/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.yami.shop.bean.app.dto.*;
import com.yami.shop.bean.app.param.OrderParam;
import com.yami.shop.bean.app.param.OrderPayInfoParam;
import com.yami.shop.bean.app.param.OrderShopParam;
import com.yami.shop.bean.app.param.SubmitOrderParam;
import com.yami.shop.bean.enums.DvyType;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.event.*;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.UserAddrOrder;
import com.yami.shop.common.constants.OrderCacheNames;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.CacheManagerUtil;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/p/order")
@Api(tags = "订单接口")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private SkuService skuService;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserAddrService userAddrService;
    @Autowired
    private BasketService basketService;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private UserAddrOrderService userAddrOrderService;

    @Autowired
    private CacheManagerUtil cacheManagerUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 生成订单
     */
    @PostMapping("/confirm")
    @ApiOperation(value = "结算，生成订单信息", notes = "传入下单所需要的参数进行下单")
    public ResponseEntity<ShopCartOrderMergerDto> confirm(@Valid @RequestBody OrderParam orderParam) {
        String userId = SecurityUtils.getUser().getUserId();
        if( Objects.isNull(orderParam.getDvyType())){
            orderParam.setDvyType(DvyType.DELIVERY.value());
        }
        // 订单的地址信息
        UserAddr userAddr = userAddrService.getUserAddrByUserId(orderParam.getAddrId(), userId);
        UserAddrDto userAddrDto = mapperFacade.map(userAddr, UserAddrDto.class);
        // 组装获取用户提交的购物车商品项
        List<ShopCartItemDto> shopCartItemsDb = basketService.getShopCartItemsByOrderItems(orderParam.getBasketIds(),orderParam.getOrderItem(),userId);
        if (CollectionUtil.isEmpty(shopCartItemsDb)) {
            // 请选择您需要的商品加入购物车
            throw new YamiShopBindException("yami.selelct.items");
        }
        // 筛选过滤掉不同配送的商品
        List<ShopCartItemDto> shopCartItems = new ArrayList<>();
        List<ShopCartItemDto> filterShopItems = filterShopItemsByType(shopCartItemsDb, shopCartItems,orderParam.getDvyType());
        // 判断是不是预售商品
        int preSellStatus = 0;
        for (ShopCartItemDto shopCartItem : shopCartItems) {
            preSellStatus = Objects.isNull(shopCartItem.getPreSellStatus()) || Objects.equals(shopCartItem.getPreSellStatus(),0)?0:1;
        }
        orderParam.setPreSellStatus(preSellStatus);

        // 根据店铺组装购车中的商品信息，返回每个店铺中的购物车商品信息
        List<ShopCartDto> shopCarts = basketService.getShopCarts(shopCartItems);

        // 将要返回给前端的完整的订单信息
        ShopCartOrderMergerDto shopCartOrderMergerDto = new ShopCartOrderMergerDto();
        shopCartOrderMergerDto.setPreSellStatus(preSellStatus);
        shopCartOrderMergerDto.setDvyType(orderParam.getDvyType());
        shopCartOrderMergerDto.setUserAddr(userAddrDto);
        shopCartOrderMergerDto.setIsScorePay(orderParam.getIsScorePay());
        // 所有店铺的订单信息
        List<ShopCartOrderDto> shopCartOrders = new ArrayList<>();
        double actualTotal = 0.0;
        double total = 0.0;
        int totalCount = 0;
        double allOrderReduce = 0.0;
        double totalTransfee = 0.0;

        //同城配送的状态
        Integer shopCityStatus = 0;

        // 所有店铺所有的商品item
        List<ShopCartItemDto> allCartItem = new ArrayList<>();

//        List<CouponOrderDto> coupons = new ArrayList<>();
        for (ShopCartDto shopCart : shopCarts) {

            // 每个店铺的订单信息
            ShopCartOrderDto shopCartOrder = new ShopCartOrderDto();
            shopCartOrder.setShopId(shopCart.getShopId());
            shopCartOrder.setShopName(shopCart.getShopName());


            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCart.getShopCartItemDiscounts();

            // 店铺中的所有商品项信息
            List<ShopCartItemDto> shopAllShopCartItems = new ArrayList<>();
            for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
                List<ShopCartItemDto> discountShopCartItems = shopCartItemDiscount.getShopCartItems();
                shopAllShopCartItems.addAll(discountShopCartItems);
            }
            shopCartOrder.setShopCartItemDiscounts(shopCartItemDiscounts);
            allCartItem.addAll(shopAllShopCartItems);

            applicationContext.publishEvent(new ConfirmOrderEvent(shopCartOrder,orderParam,shopAllShopCartItems));
//            actualTotal = Arith.add(actualTotal,shopCartOrder.getActualTotal());
            total = Arith.add(total,shopCartOrder.getTotal());
            totalCount = totalCount + shopCartOrder.getTotalCount();
            allOrderReduce = Arith.add(allOrderReduce,shopCartOrder.getShopReduce());

            totalTransfee = Arith.add(totalTransfee, shopCartOrder.getTransfee());

            shopCartOrders.add(shopCartOrder);

            shopCityStatus = shopCartOrder.getShopCityStatus();
        }
        //等级减免的金额等于运费金额
        double freeTransfee = totalTransfee;
        //根据价格进行店铺、满减、商品项的价格升序操作
        for (int n = 0; n < shopCartOrders.size(); n++) {
            shopCartOrders = shopCartOrders.stream().sorted(Comparator.comparing(ShopCartOrderDto::getActualTotal)).collect(Collectors.toList());
            ShopCartOrderDto shopCartOrderDto = shopCartOrders.get(n);

            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrderDto.getShopCartItemDiscounts();
            for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
                List<ShopCartItemDto> sortShopCartItems = shopCartItemDiscount.getShopCartItems();
                sortShopCartItems = sortShopCartItems.stream().sorted(Comparator.comparing(ProductItemDto::getActualTotal)).collect(Collectors.toList());
                shopCartItemDiscount.setShopCartItems(sortShopCartItems);
                double totalAmount = shopCartItemDiscount.getShopCartItems().stream().mapToDouble(ProductItemDto::getActualTotal).sum();
                shopCartItemDiscount.setTotalAmount(totalAmount);
            }
            // 如果是折扣特别小的情况下，导致商品实际金额为0是，改变最小支付金额为0.01元,并且优惠金额减去0.01。
            if(Arith.sub(shopCartOrderDto.getActualTotal(),shopCartOrderDto.getTransfee()) <= 0) {
                shopCartOrderDto.setActualTotal(Arith.add(shopCartOrderDto.getActualTotal(),0.01));
                shopCartOrderDto.setShopReduce(Arith.sub(shopCartOrderDto.getShopReduce(),0.01));
                List<ShopCartItemDto> sortItems = shopCartItemDiscounts.get(shopCartItemDiscounts.size() - 1).getShopCartItems();
                ShopCartItemDto shopCartItemDto = sortItems.get(sortItems.size() - 1);
                shopCartItemDto.setActualTotal(0.01);
                shopCartItemDto.setShareReduce(Arith.sub(shopCartItemDto.getShareReduce(),0.01));
            }
            shopCartItemDiscounts = shopCartItemDiscounts.stream().sorted(Comparator.comparing(ShopCartItemDiscountDto::getTotalAmount)).collect(Collectors.toList());
            shopCartOrders.get(n).setShopCartItemDiscounts(shopCartItemDiscounts);
            actualTotal = Arith.add(actualTotal,shopCartOrderDto.getActualTotal());
        }

        shopCartOrderMergerDto.setActualTotal(actualTotal);
        shopCartOrderMergerDto.setTotal(total);
        shopCartOrderMergerDto.setTotalCount(totalCount);
        shopCartOrderMergerDto.setOrderReduce(allOrderReduce);
        shopCartOrderMergerDto.setTotalTransfee(totalTransfee);
        shopCartOrderMergerDto.setUuid(orderParam.getUuid());
        shopCartOrderMergerDto.setShopCartOrders(shopCartOrders);
        shopCartOrderMergerDto.setShopCityStatus(shopCityStatus);

        applicationContext.publishEvent(new PlatformConfirmOrderEvent(shopCartOrderMergerDto,orderParam,allCartItem));

        // ============  通过订单项的金额，计算出订单总金额  ==============

        //所有订单实际金额
        actualTotal = 0.00;
        //所有订单优惠金额
        allOrderReduce = 0.00;
        totalTransfee = 0.00;
        for (ShopCartOrderDto shopCartOrder : shopCartOrders) {

            //订单实际金额
            double orderActualTotal = 0.00;
            //商家优惠金额
            double orderReduceAmount = 0.00;
            //商家优惠金额
            double orderPlatformAmount = 0.00;
            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
            for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
                for (ShopCartItemDto shopCartItem : shopCartItemDiscount.getShopCartItems()) {
                    shopCartItem.setPlatformShareReduce(Arith.round(shopCartItem.getPlatformShareReduce(),2));
                    shopCartItem.setShareReduce(Arith.add(Arith.round(shopCartItem.getShareReduce(),2),shopCartItem.getPlatformShareReduce()));
                    shopCartItem.setActualTotal(Arith.sub(shopCartItem.getProductTotalAmount(),shopCartItem.getShareReduce()));
                    orderActualTotal = Arith.add(orderActualTotal,shopCartItem.getActualTotal());
                    orderReduceAmount = Arith.add(orderReduceAmount,shopCartItem.getShareReduce());
                    orderPlatformAmount = Arith.add(orderPlatformAmount,shopCartItem.getPlatformShareReduce());
                }
            }
            shopCartOrder.setActualTotal(Arith.add(orderActualTotal,shopCartOrder.getTransfee()));
            //放入优惠金额
            shopCartOrder.setShopReduce(Arith.add(orderReduceAmount,shopCartOrder.getFreeTransfee()));
            //放入平台优惠金额,如果用户等级免自营店运费也要放进去
            shopCartOrder.setPlatformAmount(Arith.add(orderPlatformAmount,shopCartOrder.getFreeTransfee()));
            // 如果是折扣特别小的情况下，导致实际金额为0是，改变最小支付金额为0.01元,并且优惠金额减去0.01。
            if(shopCartOrder.getActualTotal() < 0.01) {
                shopCartOrder.setActualTotal(0.01);
                shopCartOrder.setPlatformAmount(Arith.sub(shopCartOrder.getPlatformAmount(),0.01));
                shopCartOrder.setShopReduce(Arith.sub(shopCartOrder.getShopReduce(),0.01));
                List<ShopCartItemDto> sortItems = shopCartItemDiscounts.get(shopCartItemDiscounts.size() - 1).getShopCartItems();
                ShopCartItemDto shopCartItemDto = sortItems.get(sortItems.size() - 1);
                shopCartItemDto.setActualTotal(0.01);
                shopCartItemDto.setPlatformShareReduce(Arith.sub(shopCartOrder.getPlatformAmount(),0.01));
                shopCartItemDto.setShareReduce(Arith.sub(shopCartItemDto.getShareReduce(),0.01));
                // 并且如果等级优惠金额不为空，则在等级优惠金额减去，否则减去平台优惠券的分摊金额
                if(shopCartOrderMergerDto.getTotalLevelAmount() > 0.00){
                    shopCartOrderMergerDto.setTotalLevelAmount(Arith.sub(shopCartOrderMergerDto.getTotalLevelAmount(),0.01));
                }
            }
            actualTotal = Arith.add(actualTotal,shopCartOrder.getActualTotal());
            allOrderReduce = Arith.add(allOrderReduce,shopCartOrder.getShopReduce());
            totalTransfee = Arith.add(totalTransfee, shopCartOrder.getTransfee());
        }
        shopCartOrderMergerDto.setActualTotal(actualTotal);
        shopCartOrderMergerDto.setOrderReduce(allOrderReduce);
        shopCartOrderMergerDto.setFilterShopItems(filterShopItems);
        shopCartOrderMergerDto.setTotalTransfee(totalTransfee);
        //如果运费为0，且减免金额不为0，说明运费已被扣减，数据库存的运费为0，但仍需返回前端展示
        if (totalTransfee == 0 && freeTransfee > 0) {
            shopCartOrderMergerDto.setTotalTransfee(freeTransfee);
        }

        // 如果是自提的话，查询出用户最近使用的几个自提用户信息
        if(orderParam.getDvyType() != null && Objects.equals(orderParam.getDvyType(),DvyType.STATION.value())){
            shopCartOrderMergerDto.setStationId(orderParam.getStationId());
            applicationContext.publishEvent(new GetUserStationEvent(userId,shopCartOrderMergerDto));
        }
        applicationContext.publishEvent(new ScoreConfirmOrderEvent(shopCartOrderMergerDto,orderParam,allCartItem));


        // 防止重复提交
        stringRedisTemplate.opsForValue().set(OrderCacheNames.ORDER_CONFIRM_UUID_KEY + OrderCacheNames.UNION  + userId, userId);
        // 保存订单计算结果缓存，省得重新计算 并且 用户确认的订单金额与提交的一致
        cacheManagerUtil.putCache(OrderCacheNames.ORDER_CONFIRM_KEY, userId,shopCartOrderMergerDto);

        return ResponseEntity.ok(shopCartOrderMergerDto);
    }

    /**
     * 过滤物流不同的商品
     * @param shopCartItems 用户选择的商品项
     * @param cartItems 过滤后的元素
     * @param dvyType 物流方式 1.为快递 2.为用户自提 4.为同城配送
     * @return 返回过滤掉的商品项item
     */
    private List<ShopCartItemDto> filterShopItemsByType(List<ShopCartItemDto> shopCartItems, List<ShopCartItemDto> cartItems, Integer dvyType) {
        List<ShopCartItemDto> filterItems = new ArrayList<>();
        for (ShopCartItemDto shopCartItem : shopCartItems) {
            Product.DeliveryModeVO deliveryModeVO = shopCartItem.getDeliveryModeVO();
            boolean hasShopDelivery = true;
            boolean hasCityDelivery = false;
            boolean hasUserPickUp = false;
            if(Objects.nonNull(deliveryModeVO)){
                hasShopDelivery = deliveryModeVO.getHasShopDelivery() != null && Objects.equals(dvyType, DvyType.DELIVERY.value()) && deliveryModeVO.getHasShopDelivery();
                hasUserPickUp =  deliveryModeVO.getHasUserPickUp() != null && Objects.equals(dvyType, DvyType.STATION.value()) && deliveryModeVO.getHasUserPickUp();
                hasCityDelivery = deliveryModeVO.getHasCityDelivery() != null && Objects.equals(dvyType, DvyType.SAME_CITY.value()) && deliveryModeVO.getHasCityDelivery();
            }
            if(hasShopDelivery || hasUserPickUp || hasCityDelivery){
                cartItems.add(shopCartItem);
            }else{
                filterItems.add(shopCartItem);
            }
        }
        return filterItems;
    }


    /**
     * 购物车/立即购买  提交订单,根据店铺拆单
     */
    @PostMapping("/submit")
    @ApiOperation(value = "提交订单，返回支付流水号", notes = "根据传入的参数判断是否为购物车提交订单，同时对购物车进行删除，用户开始进行支付")
    public ResponseEntity<OrderNumbersDto> submitOrders(@Valid @RequestBody SubmitOrderParam submitOrderParam) {
        String userId = SecurityUtils.getUser().getUserId();
        // 防止重复、同时提交
        boolean cad = RedisUtil.cad(OrderCacheNames.ORDER_CONFIRM_UUID_KEY + OrderCacheNames.UNION  + userId, userId);
        if (!cad) {
            // 订单状态已经发生改变，请重新下单
//            throw new YamiShopBindException("yami.order.status.check.change");
            OrderNumbersDto orderNumbersDto = new OrderNumbersDto(null);
            orderNumbersDto.setDuplicateError(1);
            return ResponseEntity.ok(orderNumbersDto);
        }

        // 看看订单的标记有没有过期
        if (cacheManagerUtil.getCache(OrderCacheNames.ORDER_CONFIRM_KEY,  userId) == null) {
            // 订单已过期，请重新下单
            throw new YamiShopBindException("yami.order.expired");
        }

        ShopCartOrderMergerDto mergerOrder = cacheManagerUtil.getCache(OrderCacheNames.ORDER_CONFIRM_KEY, userId);
        if (mergerOrder == null || mergerOrder.getShopCartOrders().size() < 1) {
            // 订单已过期，请重新下单
            throw new YamiShopBindException("yami.order.expired");
        }

        if(!Objects.equals(mergerOrder.getDvyType(),DvyType.DELIVERY.value()) && mergerOrder.getShopCartOrders().size() > 1){
            // 多家店铺提交订单时，配送方式只能是快递
            throw new YamiShopBindException("yami.order.delivery.error");
        }
        if(Objects.equals(mergerOrder.getDvyType(),DvyType.SAME_CITY.value())){
            if(Objects.nonNull(mergerOrder.getShopCityStatus()) && Objects.equals(mergerOrder.getShopCityStatus(),-2)) {
                // 当前店铺未开启同城配送
                throw new YamiShopBindException("yami.order.same.city.error");
            }
            if(Objects.nonNull(mergerOrder.getShopCityStatus()) && mergerOrder.getShopCityStatus() < 1){
                // 超出商家配送距离或起送费不够
                throw new YamiShopBindException("yami.order.same.city.error2");
            }
        }

        if(Objects.equals(mergerOrder.getDvyType(),DvyType.STATION.value()) && Objects.isNull(mergerOrder.getStationId()) && Objects.isNull(submitOrderParam.getOrderSelfStationDto())){
            // 请选择自提点并填写完整的自提信息
            throw new YamiShopBindException("yami.station.detail.check!");
        }
//        mergerOrder.getOrderSelfStationDto().setStationId(mergerOrder.getStationId());

        mergerOrder.setOrderSelfStationDto(submitOrderParam.getOrderSelfStationDto());
        List<OrderShopParam> orderShopParams = submitOrderParam.getOrderShopParam();

        List<ShopCartOrderDto> shopCartOrders = mergerOrder.getShopCartOrders();
        // 设置备注
        if (CollectionUtil.isNotEmpty(orderShopParams)) {
            for (ShopCartOrderDto shopCartOrder : shopCartOrders) {
                for (OrderShopParam orderShopParam : orderShopParams) {
                    if (Objects.equals(shopCartOrder.getShopId(), orderShopParam.getShopId())) {
                        shopCartOrder.setRemarks(orderShopParam.getRemarks());
                    }
                }
            }
        }

        List<Order> orders = orderService.submit(userId,mergerOrder);

        StringBuilder orderNumbers = new StringBuilder();
        for (Order order : orders) {
            orderNumbers.append(order.getOrderNumber()).append(",");
        }
        orderNumbers.deleteCharAt(orderNumbers.length() - 1);

        boolean isShopCartOrder = false;
        // 移除缓存
        for (ShopCartOrderDto shopCartOrder : shopCartOrders) {
            for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartOrder.getShopCartItemDiscounts()) {
                for (ShopCartItemDto shopCartItem : shopCartItemDiscount.getShopCartItems()) {
                    Long basketId = shopCartItem.getBasketId();
                    if (basketId != null && basketId != 0) {
                        isShopCartOrder = true;
                    }
                    skuService.removeSkuCacheBySkuIdAndLang(shopCartItem.getSkuId(),shopCartItem.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
                    skuService.removeSkuCacheBySkuIdAndLang(shopCartItem.getSkuId(),shopCartItem.getProdId(),LanguageEnum.LANGUAGE_EN.getLang());
                    productService.removeProdCacheByProdId(shopCartItem.getProdId(),LanguageEnum.LANGUAGE_ZH_CN.getLang());
                    productService.removeProdCacheByProdId(shopCartItem.getProdId(),LanguageEnum.LANGUAGE_EN.getLang());
                }
            }
        }
        // 购物车提交订单时(即有购物车ID时)
        if (isShopCartOrder) {
            basketService.removeShopCartItemsCacheByUserId(userId,LanguageEnum.LANGUAGE_ZH_CN.getLang());
            basketService.removeShopCartItemsCacheByUserId(userId,LanguageEnum.LANGUAGE_EN.getLang());
        }
        orderService.removeConfirmOrderCache(userId+submitOrderParam.getUuid());
        return ResponseEntity.ok(new OrderNumbersDto(orderNumbers.toString()));
    }


    @GetMapping("/getOrderPayInfoByOrderNumber")
    @ApiOperation(value = "获取订单支付信息", notes = "获取订单支付的商品/地址信息")
    @ApiImplicitParam(name = "orderNumbers", value = "订单流水号", required = true, dataType = "String")
    public ResponseEntity<OrderPayInfoParam> getOrderPayInfoByOrderNumber(@RequestParam("orderNumbers") String orderNumbers) {
        List<String> orderNumberList = Arrays.asList(orderNumbers.split(","));
        //获取订单信息
        List<Order> orderList = orderService.getOrderPayInfoByOrderNumber(orderNumberList);
        List<String> prodNameList = Lists.newArrayList();
        Long addrOrderId = null;
        Date endTime = null;
        int totalScore = 0;
        double totalFee = 0.0;
        boolean isStation = false;
        Integer status = 1;
        Order orderDb = new Order();
        //获取商品名集合
        for (Order order:orderList){
            for (OrderItem orderItem:order.getOrderItems()){
                prodNameList.add(orderItem.getProdName());
                totalScore += orderItem.getUseScore() != null ?orderItem.getUseScore():0;
            }
            //第一次循环，获取订单地址id，订单过期时间
            if (Objects.isNull(addrOrderId)){
                addrOrderId = order.getAddrOrderId();
                if (Objects.equals(2,order.getOrderType())) {
                    // 获取秒杀订单的取消订单时间
                    Integer maxCancelTime = 0;
                    SubmitSeckillOrderEvent event = new SubmitSeckillOrderEvent(order, maxCancelTime);
                    applicationContext.publishEvent(event);
                    maxCancelTime = event.getMaxCancelTime();
                    if (maxCancelTime <= 0) {
                        maxCancelTime = 30;
                    }
                    endTime =  DateUtil.offsetMinute(order.getCreateTime(),maxCancelTime);
                } else {
                    endTime =  DateUtil.offsetMinute(order.getCreateTime(),30);
                }
            }
            totalFee = Arith.add(totalFee,order.getActualTotal());
            if(Objects.equals(order.getDvyType(),DvyType.STATION.value())){
                isStation = true;
                orderDb = order;
            }
            if(!Objects.equals(order.getStatus(), OrderStatus.UNPAY.value())){
                status = order.getStatus();
            }
        }
        OrderPayInfoParam orderPayInfoParam = new OrderPayInfoParam();
        orderPayInfoParam.setStatus(status);
        orderPayInfoParam.setProdNameList(prodNameList);
        orderPayInfoParam.setEndTime(endTime);
        orderPayInfoParam.setTotalFee(totalFee);
        orderPayInfoParam.setTotalScore(totalScore);
        if(isStation){
            orderPayInfoParam.setUserAddr("");
            orderPayInfoParam.setReceiver(orderDb.getReceiverName());
            orderPayInfoParam.setMobile(orderDb.getReceiverMobile());
        }else {
            //写入商品名、收货地址/电话
            UserAddrOrder userAddrOrder = userAddrOrderService.getById(addrOrderId);
            String addr = userAddrOrder.getProvince() + userAddrOrder.getCity() + userAddrOrder.getArea() + userAddrOrder.getAddr();
            orderPayInfoParam.setUserAddr(addr);
            orderPayInfoParam.setReceiver(userAddrOrder.getReceiver());
            orderPayInfoParam.setMobile(userAddrOrder.getMobile());
        }
        return ResponseEntity.ok(orderPayInfoParam);
    }

}
